<template>
  <div class="reg">
    <van-nav-bar left-text="返回" left-arrow @click-left="onClickLeft" />
    <h1>登录</h1>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userName"
        name="pattern"
        label="手机号"
        placeholder="手机号"
        :rules="[{ pattern, required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="validator"
        label="密码"
        placeholder="密码"
        :rules="[{ validator, required: true, message: '请填写密码' }]"
      />
      <div style="margin: 50px  16px 16px;">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
    <p>没有账号? <span @click="regHandle">注册</span></p>
  </div>
</template>

<script>
import { LoginApi } from "../services/auth";
import { Toast } from "vant";
import {setToken} from '../utils/tools'
export default {
  data() {
    return {
      password: "",
      userName: "",
      repwd: "",
      pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
    };
  },
  methods: {
    validator(val) {
      return /^\d{6}$/.test(val);
    },
    regHandle() {
      this.$router.push({
        name: "Reg",
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    async onSubmit() {
      const res = await LoginApi({
        userName: this.userName,
        password: this.password,
      });
      if (res.code == 1) {
        setToken(res.data)
        Toast.success("登录成功");
        this.$router.push({
          name:'Home'
        })
      } else {
        Toast.fail(res.data);
      }
    },
  },
};
</script>

<style scoped>
h1 {
  font-size: 1.5rem;
  margin-left: 1rem;
  margin-bottom: 2rem;
  margin-top: 2rem;
}
.van-field {
  margin-bottom: 1rem;
}

p {
  position: fixed;
  bottom: 50px;
  left: 35%;
}
p span {
  color: rgba(123, 123, 214, 0.747);
}
</style>
